package com.itheima.tlias.aspect;

import com.itheima.tlias.mapper.EmpLogMapper;
import com.itheima.tlias.pojo.Emp;
import com.itheima.tlias.pojo.EmpLoginLog;
import com.itheima.tlias.pojo.LoginInfo;
import com.itheima.tlias.pojo.Result;
import com.itheima.tlias.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 登录日志切面
 *
 * @Author mr.luo
 * @Date 19 4月 2025 09:31
 */
@Slf4j
@Aspect
@Component
public class LoginLogAspect {
    @Autowired
    private EmpLogMapper empLogMapper;

    @Around("execution(* com.itheima.tlias.controller.LoginController.login(..))")
    public Object optLogHandle(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        log.info("[日志记录切面]记录登录日志信息");
        //封装登录日志
        EmpLoginLog empLoginLog = new EmpLoginLog();
        //获取用户登录id
        empLoginLog.setId(BaseContext.get());
        //获取用户名
        Object[] args = proceedingJoinPoint.getArgs();
        Emp emp = (Emp) args[0];
        empLoginLog.setUsername(emp.getUsername());
        //设置登录密码
        empLoginLog.setPassword(emp.getPassword());
        //设置登录时间
        empLoginLog.setLoginTime(LocalDateTime.now());
        long start = System.currentTimeMillis();
        Object returnResult = proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();
//        设置耗时
        empLoginLog.setCostTime(end - start);
        //设置是否登录成功
        Result result = (Result) returnResult;
        Short code = Short.valueOf(String.valueOf(result.getCode()));
        empLoginLog.setIsSuccess(code);
        //设置JWT
        LoginInfo loginInfo = (LoginInfo) result.getData();
        String token = loginInfo!=null?loginInfo.getToken():null;
        empLoginLog.setJwt(token);
        //进行插入日志
        empLogMapper.insertLoginLog(empLoginLog);

        log.info("[日志记录切面]记录成功日志信息:{}",empLoginLog);
        return returnResult;
    }
}
